document.addEventListener('DOMContentLoaded', function() {
    // 检查当前是否为/watch页面（通过检查关键元素是否存在）
    const videoPlayer = document.getElementById('video-player');
    if (!videoPlayer) {
        // 在首页或其他不包含视频播放功能的页面，不初始化视频相关功能
        console.log('非视频播放页面，跳过视频功能初始化');
        return;
    }
    
    // 获取DOM元素
    const fileUpload = document.getElementById('file-upload');
    const uploadBtn = document.getElementById('upload-btn');
    const uploadStatus = document.getElementById('upload-status');
    const playBtn = document.getElementById('play-btn');
    const pauseBtn = document.getElementById('pause-btn');
    const progressBar = document.getElementById('progress-bar');
    const timeDisplay = document.getElementById('time-display');
    const roomInfo = document.getElementById('room-info');
    
    // 视频选择模态框元素
    const selectVideoBtn = document.getElementById('select-video-btn');
    const videoModal = document.getElementById('video-modal');
    const closeBtn = document.querySelector('.close-btn');
    const closeModalBtn = document.getElementById('close-modal-btn');
    const videoListLoading = document.getElementById('video-list-loading');
    const videoList = document.getElementById('video-list');
    const videoListEmpty = document.getElementById('video-list-empty');
    const videoSelectionStatus = document.getElementById('video-selection-status');
    
    // 评分系统元素
    const overallStars = document.getElementById('overall-stars');
    const plotStars = document.getElementById('plot-stars');
    const actorsStars = document.getElementById('actors-stars');
    const soundStars = document.getElementById('sound-stars');
    const overallRating = document.getElementById('overall-rating');
    const plotRating = document.getElementById('plot-rating');
    const actorsRating = document.getElementById('actors-rating');
    const soundRating = document.getElementById('sound-rating');
    const ratingCount = document.getElementById('rating-count');
    
    // 评分输入元素
    const overallInput = document.getElementById('overall-input');
    const plotInput = document.getElementById('plot-input');
    const actorsInput = document.getElementById('actors-input');
    const soundInput = document.getElementById('sound-input');
    const overallRatingValue = document.getElementById('overall-rating-value');
    const plotRatingValue = document.getElementById('plot-rating-value');
    const actorsRatingValue = document.getElementById('actors-rating-value');
    const soundRatingValue = document.getElementById('sound-rating-value');
    const submitRatingBtn = document.getElementById('submit-rating-btn');
    const ratingStatus = document.getElementById('rating-status');
    
    // 全局变量
    let socket = null;
    let isDragging = false;
    let socketEventActive = false; // 用于标记是否正在处理socket事件，防止循环
    
    // 创建Socket.IO连接
    function initSocket() {
        if (socket) return;
        
        socket = io();
        
        // Socket事件处理
        socket.on('connect', () => {
            console.log('Socket已连接');
            joinRoom();
        });
        
        socket.on('disconnect', () => {
            console.log('Socket已断开连接');
        });
        
        socket.on('room_status', (roomData) => {
            console.log('房间状态:', roomData);
            if (roomData.video_filename && roomData.video_filename.trim()) {
                const videoUrl = `/videos/${roomData.video_filename}`;
                videoPlayer.src = videoUrl;
                videoPlayer.currentTime = roomData.current_time || 0;
                
                if (roomData.status === 'playing') {
                    videoPlayer.play();
                } else if (roomData.status === 'paused') {
                    videoPlayer.pause();
                }
            } else {
                // 清空视频源，避免显示默认视频
                videoPlayer.src = '';
                videoPlayer.currentTime = 0;
                updateTimeDisplay();
            }
        });
        
        socket.on('video_uploaded', (data) => {
            console.log('视频已上传:', data);
            const videoUrl = `/videos/${data.filename}`;
            videoPlayer.src = videoUrl;
            updateTimeDisplay();
        });
        
        socket.on('play', (data) => {
            console.log('接收到播放命令:', data);
            // 设置标志防止循环
            socketEventActive = true;
            
            // 先更新时间，再尝试播放
            videoPlayer.currentTime = data.current_time || 0;
            
            // 使用Promise方式处理播放操作，增强兼容性
            const playPromise = videoPlayer.play();
            if (playPromise !== undefined) {
                playPromise.catch(error => {
                    console.warn('播放失败，可能是用户交互限制:', error);
                    // 在移动端，播放失败可能是由于用户交互限制导致
                    // 这里不做额外处理，让用户手动触发播放
                });
            }
            
            // 处理完成后重置标志
            setTimeout(() => socketEventActive = false, 150);
        });
        
        socket.on('pause', (data) => {
            console.log('接收到暂停命令:', data);
            // 设置标志防止循环
            socketEventActive = true;
            
            // 更新时间并暂停
            videoPlayer.currentTime = data.current_time || 0;
            videoPlayer.pause();
            
            // 处理完成后重置标志
            setTimeout(() => socketEventActive = false, 150);
        });
        
        socket.on('seek', (data) => {
            console.log('接收到进度调整命令:', data);
            if (!isDragging) {
                // 设置标志防止循环
                socketEventActive = true;
                
                // 平滑设置视频时间
                const targetTime = data.current_time || 0;
                // 添加时间差异检查，如果差异很小则不调整，避免过度同步
                if (Math.abs(videoPlayer.currentTime - targetTime) > 0.5) {
                    videoPlayer.currentTime = targetTime;
                }
                
                enhancedProgressUpdate();
                // 处理完成后重置标志，延长时间避免循环
                setTimeout(() => socketEventActive = false, 200);
              }
        });
        
        socket.on('error', (data) => {
            console.error('错误:', data);
            alert(data.message || '发生错误');
        });
        
        socket.on('rating_update', (ratingsData) => {
            console.log('接收到评分更新:', ratingsData);
            // 更新显示评分
            overallRating.textContent = ratingsData.overall.toFixed(1);
            plotRating.textContent = ratingsData.plot.toFixed(1);
            actorsRating.textContent = ratingsData.actors.toFixed(1);
            soundRating.textContent = ratingsData.sound.toFixed(1);
            ratingCount.textContent = ratingsData.count;
            
            // 更新星星显示
            updateStarDisplay(overallStars, ratingsData.overall);
            updateStarDisplay(plotStars, ratingsData.plot);
            updateStarDisplay(actorsStars, ratingsData.actors);
            updateStarDisplay(soundStars, ratingsData.sound);
        });
    }
    
    // 加入房间
    function joinRoom() {
        if (!socket) {
            initSocket();
        }
        
        socket.emit('join');
        roomInfo.textContent = '已连接到共享观看房间';
    }
    
    // 星星评分交互 - 修改为从左往右评分
    function setupStarRating() {
        // 为输入星星添加事件监听器
        const starInputs = document.querySelectorAll('.star-input');
        starInputs.forEach(star => {
            star.addEventListener('click', function() {
                const value = parseInt(this.getAttribute('data-value'));
                const parent = this.parentElement;
                const hiddenInput = parent.nextElementSibling;
                
                // 更新隐藏输入框的值
                hiddenInput.value = value;
                
                // 更新星星显示 - 从左往右评分逻辑
                const stars = parent.querySelectorAll('.star-input');
                stars.forEach((s, index) => {
                    // 从左往右评分：如果索引小于评分值，则显示实心星星
                    if (index < value) {
                        s.textContent = '★';
                        s.classList.add('active');
                    } else {
                        s.textContent = '☆';
                        s.classList.remove('active');
                    }
                });
            });
            
            // 添加鼠标悬停效果，增强用户体验
            star.addEventListener('mouseenter', function() {
                const value = parseInt(this.getAttribute('data-value'));
                const parent = this.parentElement;
                const stars = parent.querySelectorAll('.star-input');
                
                stars.forEach((s, index) => {
                    if (index < value) {
                        s.textContent = '★';
                    }
                });
            });
            
            star.addEventListener('mouseleave', function() {
                const parent = this.parentElement;
                const hiddenInput = parent.nextElementSibling;
                const currentValue = parseInt(hiddenInput.value) || 0;
                const stars = parent.querySelectorAll('.star-input');
                
                stars.forEach((s, index) => {
                    if (index < currentValue) {
                        s.textContent = '★';
                    } else {
                        s.textContent = '☆';
                    }
                });
            });
        });
    }
    
    // 更新显示评分的星星 - 适配从左到右评分
    function updateStarDisplay(starContainer, rating) {
        const stars = starContainer.querySelectorAll('.star');
        const fullStars = Math.floor(rating);
        const halfStar = rating % 1 >= 0.5;
        
        // 重置所有星星
        stars.forEach(star => {
            star.classList.remove('filled');
            star.textContent = '☆'; // 默认显示空心星星
        });
        
        // 从左到右设置实心星星
        stars.forEach((star, index) => {
            if (index < fullStars) {
                star.classList.add('filled');
                star.textContent = '★'; // 实心星星
            } else if (index === fullStars && halfStar) {
                // 可以考虑添加半星显示逻辑，但这里保持简单使用实心星星
                star.classList.add('filled');
                star.textContent = '★'; // 实心星星
            }
        });
    }
    
    // 提交评分
    submitRatingBtn.addEventListener('click', async function() {
        const overall = parseInt(overallRatingValue.value);
        const plot = parseInt(plotRatingValue.value);
        const actors = parseInt(actorsRatingValue.value);
        const sound = parseInt(soundRatingValue.value);
        
        // 验证输入
        if (overall === 0 || plot === 0 || actors === 0 || sound === 0) {
            ratingStatus.textContent = '请为所有评分项打分';
            ratingStatus.style.color = '#e74c3c';
            return;
        }
        
        // 直接使用1-5分评分系统
        const ratingsData = {
            overall: overall,
            plot: plot,
            actors: actors,
            sound: sound
        };
        
        try {
            const response = await fetch('/rating', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(ratingsData)
            });
            
            const result = await response.json();
            
            if (result.success) {
                ratingStatus.textContent = '评分提交成功！';
                ratingStatus.style.color = '#27ae60';
                
                // 清空输入框
                overallRatingValue.value = 0;
                plotRatingValue.value = 0;
                actorsRatingValue.value = 0;
                soundRatingValue.value = 0;
                
                // 重置星星显示
                const starInputs = document.querySelectorAll('.star-input');
                starInputs.forEach(star => {
                    star.textContent = '☆';
                });
                
                // 更新显示
                overallRating.textContent = result.ratings.overall.toFixed(1);
                plotRating.textContent = result.ratings.plot.toFixed(1);
                actorsRating.textContent = result.ratings.actors.toFixed(1);
                soundRating.textContent = result.ratings.sound.toFixed(1);
                ratingCount.textContent = result.count;
                
                // 更新星星显示
                updateStarDisplay(overallStars, result.ratings.overall);
                updateStarDisplay(plotStars, result.ratings.plot);
                updateStarDisplay(actorsStars, result.ratings.actors);
                updateStarDisplay(soundStars, result.ratings.sound);
            } else {
                ratingStatus.textContent = result.error || '评分提交失败';
                ratingStatus.style.color = '#e74c3c';
            }
        } catch (error) {
            console.error('评分提交错误:', error);
            ratingStatus.textContent = '评分提交失败，请重试';
            ratingStatus.style.color = '#e74c3c';
        }
    });
    
    // 上传视频 - 分片上传模式
    uploadBtn.addEventListener('click', async function() {
        const file = fileUpload.files[0];
        if (!file) {
            alert('请选择要上传的视频文件');
            return;
        }
        
        // 显示上传状态
        uploadStatus.textContent = '准备上传...';
        console.log(`开始上传文件: ${file.name}, 大小: ${formatFileSize(file.size)}`);
        
        // 分片大小设置为5MB，可根据需要调整
        const CHUNK_SIZE = 5 * 1024 * 1024;
        const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
        let uploadedChunks = 0;
        let fileId = null;
        
        try {
            // 1. 初始化上传
            uploadStatus.textContent = '初始化上传...';
            const initResponse = await initUpload(file.name, totalChunks);
            if (!initResponse.success) {
                throw new Error(initResponse.error || '初始化上传失败');
            }
            fileId = initResponse.file_id;
            console.log('上传初始化成功，文件ID:', fileId);
            
            // 2. 上传所有分片
            for (let i = 0; i < totalChunks; i++) {
                const start = i * CHUNK_SIZE;
                const end = Math.min(start + CHUNK_SIZE, file.size);
                const chunk = file.slice(start, end);
                
                // 更新状态
                const currentProgress = (i / totalChunks) * 100;
                uploadStatus.textContent = `上传分片 ${i + 1}/${totalChunks} (${currentProgress.toFixed(1)}%)`;
                
                // 上传分片
                const chunkResponse = await uploadChunk(fileId, i, chunk);
                if (!chunkResponse.success) {
                    throw new Error(chunkResponse.error || `分片 ${i} 上传失败`);
                }
                
                uploadedChunks++;
                console.log(`分片 ${i} 上传成功，已上传: ${uploadedChunks}/${totalChunks}`);
            }
            
            // 3. 完成上传，合并分片
            uploadStatus.textContent = '合并文件中...';
            const completeResponse = await completeUpload(fileId);
            if (!completeResponse.success) {
                throw new Error(completeResponse.error || '合并文件失败');
            }
            
            // 上传成功
            uploadStatus.textContent = '上传成功';
            updateTimeDisplay();
            console.log('文件上传完成');
        } catch (error) {
            console.error('上传错误:', error);
            uploadStatus.textContent = `上传失败: ${error.message}`;
            
            // 上传失败时尝试清理
            if (fileId) {
                console.log('尝试清理未完成的上传');
                // 这里可以添加一个清理API调用
            }
        }
    });
    
    // 初始化上传
    async function initUpload(filename, totalChunks) {
        try {
            const response = await fetch('/upload/init', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    filename: filename,
                    total_chunks: totalChunks
                })
            });
            
            if (!response.ok) {
                throw new Error(`HTTP错误 ${response.status}`);
            }
            
            return await response.json();
        } catch (error) {
            console.error('初始化上传错误:', error);
            throw error;
        }
    }
    
    // 上传单个分片
    async function uploadChunk(fileId, chunkIndex, chunk) {
        try {
            const formData = new FormData();
            formData.append('file_id', fileId);
            formData.append('chunk_index', chunkIndex);
            formData.append('chunk', chunk);
            
            const response = await fetch('/upload/chunk', {
                method: 'POST',
                body: formData
            });
            
            if (!response.ok) {
                throw new Error(`HTTP错误 ${response.status}`);
            }
            
            return await response.json();
        } catch (error) {
            console.error(`上传分片 ${chunkIndex} 错误:`, error);
            throw error;
        }
    }
    
    // 完成上传
    async function completeUpload(fileId) {
        try {
            const response = await fetch('/upload/complete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    file_id: fileId
                })
            });
            
            if (!response.ok) {
                throw new Error(`HTTP错误 ${response.status}`);
            }
            
            return await response.json();
        } catch (error) {
            console.error('完成上传错误:', error);
            throw error;
        }
    }
    
    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    // 播放控制 - 只执行播放/暂停操作，socket事件由视频元素的play/pause事件处理
    playBtn.addEventListener('click', function() {
        videoPlayer.play();
    });
    
    pauseBtn.addEventListener('click', function() {
        videoPlayer.pause();
    });
    
    // 时间和进度更新使用enhancedProgressUpdate函数
    
    // 更新时间显示
    function updateTimeDisplay() {
        const current = formatTime(videoPlayer.currentTime);
        const duration = formatTime(videoPlayer.duration);
        timeDisplay.textContent = `${current} / ${duration}`;
    }
    
    // 格式化时间
    function formatTime(seconds) {
        if (isNaN(seconds)) return '00:00';
        const minutes = Math.floor(seconds / 60);
        const secs = Math.floor(seconds % 60);
        return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }
    
    // 进度条拖拽
    progressBar.addEventListener('mousedown', function() {
        isDragging = true;
    });
    
    progressBar.addEventListener('touchstart', function() {
        isDragging = true;
    });
    
    document.addEventListener('mouseup', function() {
        if (isDragging) {
            isDragging = false;
            updateVideoTime();
        }
    });
    
    document.addEventListener('touchend', function() {
        if (isDragging) {
            isDragging = false;
            updateVideoTime();
        }
    });
    
    progressBar.addEventListener('input', function() {
        if (isDragging) {
            updateTimeDisplay();
        }
    });
    
    // 更新视频时间
    function updateVideoTime() {
        const seekTime = (progressBar.value / 100) * videoPlayer.duration;
        
        // 添加时间差异检查，如果差异很小则不调整，避免过度同步
        if (Math.abs(videoPlayer.currentTime - seekTime) > 0.5) {
            // 先检查并发送socket事件
            if (socket && !socketEventActive) {
                socket.emit('seek', {
                    current_time: seekTime
                });
            }
            
            // 设置标志防止循环
            socketEventActive = true;
            videoPlayer.currentTime = seekTime;
            
            // 处理完成后重置标志，延长时间避免循环
            setTimeout(() => socketEventActive = false, 200);
        }
    }
    
    // 视频时间更新事件 - 使用增强版的进度条更新函数
    videoPlayer.addEventListener('timeupdate', enhancedProgressUpdate);
    
    // 视频元数据加载完成
    videoPlayer.addEventListener('loadedmetadata', function() {
        progressBar.max = 100;
        progressBar.value = 0;
        updateTimeDisplay();
    });
    
    // 视频播放事件 - 优化移动端兼容性
    videoPlayer.addEventListener('play', function() {
        // 主动更新进度条，确保进度条正常显示
        enhancedProgressUpdate();
        
        // 先检查socketEventActive再设置标志，确保事件能正确发送
        if (socket && !socketEventActive) {
            // 立即发送播放事件
            socket.emit('play', {
                current_time: videoPlayer.currentTime
            });
            
            // 设置标志防止循环
            socketEventActive = true;
            setTimeout(() => socketEventActive = false, 150); // 延长一点时间以确保事件完成
        }
    });
    
    // 视频暂停事件 - 优化移动端兼容性
    videoPlayer.addEventListener('pause', function() {
        // 先检查socketEventActive再设置标志，确保事件能正确发送
        if (socket && !socketEventActive) {
            // 立即发送暂停事件
            socket.emit('pause', {
                current_time: videoPlayer.currentTime
            });
            
            // 设置标志防止循环
            socketEventActive = true;
            setTimeout(() => socketEventActive = false, 150); // 延长一点时间以确保事件完成
        }
    });
    
    // 增强移动端兼容性：添加playing事件支持（适用于Android设备）
    videoPlayer.addEventListener('playing', function() {
        if (socket && !socketEventActive) {
            // 检查是否真正在播放状态
            if (!videoPlayer.paused) {
                socket.emit('play', {
                    current_time: videoPlayer.currentTime
                });
                
                socketEventActive = true;
                setTimeout(() => socketEventActive = false, 150);
            }
        }
    });
    
    // 增强移动端兼容性：添加waiting事件支持（适用于网络中断恢复）
    videoPlayer.addEventListener('waiting', function() {
        if (socket && !socketEventActive) {
            socket.emit('pause', {
                current_time: videoPlayer.currentTime
            });
            
            socketEventActive = true;
            setTimeout(() => socketEventActive = false, 150);
        }
    });
    
    // 添加webkitplay和webkitpause事件支持，增强iOS兼容性
    if (videoPlayer.addEventListener) {
        videoPlayer.addEventListener('webkitplay', function() {
            // iOS设备兼容性处理
            if (socket && !socketEventActive) {
                socket.emit('play', {
                    current_time: videoPlayer.currentTime
                });
                
                socketEventActive = true;
                setTimeout(() => socketEventActive = false, 150);
            }
        }, false);
        
        videoPlayer.addEventListener('webkitpause', function() {
            // iOS设备兼容性处理
            if (socket && !socketEventActive) {
                socket.emit('pause', {
                    current_time: videoPlayer.currentTime
                });
                
                socketEventActive = true;
                setTimeout(() => socketEventActive = false, 150);
            }
        }, false);
        
        // 增强iOS设备兼容性：添加playstart事件支持
        videoPlayer.addEventListener('playstart', function() {
            if (socket && !socketEventActive) {
                socket.emit('play', {
                    current_time: videoPlayer.currentTime
                });
                
                socketEventActive = true;
                setTimeout(() => socketEventActive = false, 150);
            }
        }, false);
    }
    
    // 视频进度调整事件
    videoPlayer.addEventListener('seeked', function() {
        // 只有在用户操作触发时才发送socket事件，避免循环
        if (socket && !isDragging && !socketEventActive) {
            socket.emit('seek', {
                current_time: videoPlayer.currentTime
            });
        }
    });
    
    // 添加触摸事件支持，增强移动设备兼容性
    videoPlayer.addEventListener('touchstart', function(e) {
        // 防止事件冒泡
        e.preventDefault();
        
        // 检查是否正在处理socket事件，如果是则不响应触摸
        if (!socketEventActive) {
            // 切换播放/暂停状态
            if (videoPlayer.paused) {
                // 使用Promise方式处理播放操作
                const playPromise = videoPlayer.play();
                if (playPromise !== undefined) {
                    playPromise.catch(error => {
                        console.warn('播放失败，可能是用户交互限制:', error);
                    });
                }
            } else {
                videoPlayer.pause();
            }
        }
    }, { passive: false });
    
    // 增强进度条更新机制，确保即使在各种情况下都能正常工作
    function enhancedProgressUpdate() {
        // 无条件更新进度条和时间显示，不再依赖isDragging状态
        const percent = (videoPlayer.currentTime / videoPlayer.duration) * 100;
        progressBar.value = isNaN(percent) ? 0 : percent;
        updateTimeDisplay();
    }
    
    // 视频播放结束
    videoPlayer.addEventListener('ended', function() {
        if (socket) {
            socket.emit('pause', {
                current_time: 0
            });
        }
    });
    
    // 处理全屏模式下的视频控制事件
    function handleFullscreenEvents() {
        // 监听全屏变化事件
        document.addEventListener('fullscreenchange', updateFullscreenVideoEvents);
        document.addEventListener('webkitfullscreenchange', updateFullscreenVideoEvents);
        document.addEventListener('mozfullscreenchange', updateFullscreenVideoEvents);
        document.addEventListener('MSFullscreenChange', updateFullscreenVideoEvents);
    }
    
    // 更新全屏视频的事件监听器 - 增强版，确保在移动设备上也能正常工作
    function updateFullscreenVideoEvents() {
        // 获取当前全屏元素
        const fullscreenElement = document.fullscreenElement || 
                                  document.webkitFullscreenElement || 
                                  document.mozFullScreenElement || 
                                  document.msFullscreenElement;
        
        // 如果存在全屏元素且是视频元素或包含视频元素
        if (fullscreenElement) {
            let fullscreenVideo;
            
            if (fullscreenElement.tagName.toLowerCase() === 'video') {
                fullscreenVideo = fullscreenElement;
            } else {
                fullscreenVideo = fullscreenElement.querySelector('video');
            }
            
            if (fullscreenVideo) {
                console.log('检测到全屏视频，确保事件监听器正常工作');
                
                // 为全屏视频重新绑定所有必要的事件监听器
                // 移除可能存在的旧监听器
                fullscreenVideo.removeEventListener('play', videoPlayer.play);
                fullscreenVideo.removeEventListener('pause', videoPlayer.pause);
                fullscreenVideo.removeEventListener('timeupdate', enhancedProgressUpdate);
                
                // 重新绑定事件监听器
                fullscreenVideo.addEventListener('play', function() {
                    // 更新进度条
                    enhancedProgressUpdate();
                    
                    // 先检查socketEventActive再设置标志，确保事件能正确发送
                    if (socket && !socketEventActive) {
                        // 立即发送播放事件
                        socket.emit('play', { current_time: fullscreenVideo.currentTime });
                        
                        // 设置标志防止循环
                        socketEventActive = true;
                        setTimeout(() => socketEventActive = false, 150);
                    }
                    
                    // 同步到原始视频元素（避免触发额外事件）
                    if (videoPlayer !== fullscreenVideo && videoPlayer.readyState >= 1) {
                        // 这里不设置socketEventActive，因为这是内部同步操作
                        // 只更新时间，不播放/暂停，避免事件循环
                        videoPlayer.currentTime = fullscreenVideo.currentTime;
                    }
                });
                
                fullscreenVideo.addEventListener('pause', function() {
                    // 先检查socketEventActive再设置标志，确保事件能正确发送
                    if (socket && !socketEventActive) {
                        // 立即发送暂停事件
                        socket.emit('pause', { current_time: fullscreenVideo.currentTime });
                        
                        // 设置标志防止循环
                        socketEventActive = true;
                        setTimeout(() => socketEventActive = false, 150);
                    }
                    
                    // 同步到原始视频元素（避免触发额外事件）
                    if (videoPlayer !== fullscreenVideo && videoPlayer.readyState >= 1) {
                        // 这里不设置socketEventActive，因为这是内部同步操作
                        // 只更新时间，不播放/暂停，避免事件循环
                        videoPlayer.currentTime = fullscreenVideo.currentTime;
                    }
                });
                
                fullscreenVideo.addEventListener('timeupdate', enhancedProgressUpdate);
                
                // 添加触摸事件支持
                fullscreenVideo.addEventListener('touchstart', function(e) {
                    e.preventDefault();
                    
                    // 检查是否正在处理socket事件，如果是则不响应触摸
                    if (!socketEventActive) {
                        if (fullscreenVideo.paused) {
                            // 使用Promise方式处理播放操作
                            const playPromise = fullscreenVideo.play();
                            if (playPromise !== undefined) {
                                playPromise.catch(error => {
                                    console.warn('全屏模式下播放失败:', error);
                                });
                            }
                        } else {
                            fullscreenVideo.pause();
                        }
                    }
                }, { passive: false });
            }
        }
    }
    
    // 定期同步视频状态（每2秒）
    setInterval(function() {
        if (socket && videoPlayer.readyState >= 1) {
            // 只有当视频加载完成后才同步
            const syncData = {
                current_time: videoPlayer.currentTime,
                paused: videoPlayer.paused
            };
            socket.emit('sync_status', syncData);
        }
    }, 2000);
    
    // 视频选择模态框功能
    function setupVideoSelectionModal() {
        // 打开模态框
        selectVideoBtn.addEventListener('click', function() {
            videoModal.style.display = 'flex';
            loadVideoList();
        });
        
        // 关闭模态框的几种方式
        closeModalBtn.addEventListener('click', closeModal);
        closeBtn.addEventListener('click', closeModal);
        
        // 点击模态框外部关闭
        window.addEventListener('click', function(event) {
            if (event.target === videoModal) {
                closeModal();
            }
        });
        
        // 按ESC键关闭
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape' && videoModal.style.display === 'flex') {
                closeModal();
            }
        });
    }
    
    // 关闭模态框
    function closeModal() {
        videoModal.style.display = 'none';
        videoSelectionStatus.textContent = '';
    }
    
    // 加载视频列表
    async function loadVideoList() {
        videoListLoading.style.display = 'block';
        videoList.style.display = 'none';
        videoListEmpty.style.display = 'none';
        videoList.innerHTML = '';
        
        try {
            const response = await fetch('/api/videos');
            const result = await response.json();
            
            if (result.success) {
                const videos = result.videos;
                
                if (videos.length === 0) {
                    videoListEmpty.style.display = 'block';
                } else {
                    videoList.style.display = 'block';
                    videos.forEach(video => {
                        const li = document.createElement('li');
                        li.className = 'video-item';
                        
                        const filenameSpan = document.createElement('span');
                        filenameSpan.className = 'video-filename';
                        filenameSpan.textContent = video.filename;
                        
                        const sizeSpan = document.createElement('span');
                        sizeSpan.className = 'video-size';
                        sizeSpan.textContent = formatFileSize(video.size);
                        
                        const selectBtn = document.createElement('button');
                        selectBtn.className = 'select-btn';
                        selectBtn.textContent = '选择';
                        selectBtn.addEventListener('click', function() {
                            selectVideo(video.filename);
                        });
                        
                        li.appendChild(filenameSpan);
                        li.appendChild(sizeSpan);
                        li.appendChild(selectBtn);
                        videoList.appendChild(li);
                    });
                }
            } else {
                videoListEmpty.style.display = 'block';
                videoListEmpty.textContent = '加载视频失败: ' + (result.error || '未知错误');
            }
        } catch (error) {
            console.error('加载视频列表错误:', error);
            videoListEmpty.style.display = 'block';
            videoListEmpty.textContent = '加载视频失败: ' + error.message;
        } finally {
            videoListLoading.style.display = 'none';
        }
    }
    
    // 选择视频
    async function selectVideo(filename) {
        videoSelectionStatus.textContent = '正在选择视频...';
        videoSelectionStatus.style.color = '#3498db';
        
        try {
            const response = await fetch('/api/select-video', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ filename: filename })
            });
            
            const result = await response.json();
            
            if (result.success) {
                videoSelectionStatus.textContent = '视频选择成功！';
                videoSelectionStatus.style.color = '#27ae60';
                
                // 延迟关闭模态框，让用户看到成功消息
                setTimeout(() => {
                    closeModal();
                }, 1500);
            } else {
                videoSelectionStatus.textContent = '选择失败: ' + (result.error || '未知错误');
                videoSelectionStatus.style.color = '#e74c3c';
            }
        } catch (error) {
            console.error('选择视频错误:', error);
            videoSelectionStatus.textContent = '选择失败: ' + error.message;
            videoSelectionStatus.style.color = '#e74c3c';
        }
    }
    
    // 初始化星星评分
    setupStarRating();
    
    // 初始化视频选择模态框
    setupVideoSelectionModal();
    
    // 初始化连接到默认房间
    initSocket();
    
    // 初始化全屏事件处理
    handleFullscreenEvents();
    
    console.log('视频同步观看功能已初始化完成，当前页面路径:', window.location.pathname);
});